import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        newCheck.main(args);
    }/*{

        Date sdate = new Date();
        Integer keyCounter = 0;
        Integer fileCounter = 0;
        FileInputStream a = null;
        InputStreamReader b = null;
        BufferedReader c = null;

        String basePath = System.getProperty("user.dir");
        //String basePath = "C:\\Users\\jingwen_zhu\\Desktop\\MesLogChecker";
        //路径配置
        String pathUrl = basePath + "\\config\\path.xml";
        //关键词配置
        String keyWordUrl = basePath + "\\config\\keyword.xml";
        //过滤词配置
        String filterUrl = basePath + "\\config\\filter.xml";
        //结果路径
        String resultUrl = basePath + "\\result\\result.xml";

        try {
            File resultFile = new File(resultUrl);
            if (!resultFile.exists()) {
                resultFile.createNewFile();
            }
            //设置结果文件编码为UTF8
            OutputStreamWriter bw = new OutputStreamWriter(new FileOutputStream(resultFile), StandardCharsets.UTF_8);
            List<String> pathList = Xml2List(pathUrl, "path");
            List<String> keyWordList = Xml2List(keyWordUrl, "keyword");
            List<String> filterList = Xml2List(filterUrl, "filter");
            //移除第一个，XML中第一个Element为模板
            pathList.remove(0);
            keyWordList.remove(0);
            Map<Object, List<Object>> mapFile = new HashMap<>();

            for (String path : pathList) {
                File file = new File(path);
                File[] fs;
                if (file.isFile()) {
                    fs = new File[]{file};
                } else {
                    fs = file.listFiles();
                }
                String lines = "";
                for (File f : fs) {
                    if (null == f || 0 == f.length() || !f.exists()) {
                        continue;
                    }
                    if (new Date().getTime() - f.lastModified() > 7 * 24 * 60 * 60 * 1000) {
                        continue;
                    }
                    //获取文件编码格式
                    String charsetType = getFileCharsetName(f);
                    List<Object> list = new ArrayList<>();
                    a = new FileInputStream(f);
                    //设置文件编码，防止乱码
                    b = new InputStreamReader(a, charsetType);
                    c = new BufferedReader(b);
                    int rowNumber = 0;
                    while ((lines = c.readLine()) != null) {
                        rowNumber++;
                        for (int i = 0; i < keyWordList.size(); i++) {
                            if (lines.contains(keyWordList.get(i))) {
                                int count = 0;
                                for (int j = 0; j < filterList.size(); j++) {
                                    if (lines.contains(filterList.get(j))) {
                                        count++;
                                    }
                                }
                                if (count == 0) {
                                    list.add("lineNum:" + rowNumber + ":" + lines);
                                    keyCounter++;
                                }
                            }
                        }
                    }
                    mapFile.put(f, list);
                    fileCounter++;
                }

            }
            Object[] list = mapFile.keySet().toArray();
            //写入结果文件
            for (int i = 0; i < list.length; i++) {
                if (!mapFile.get(list[i]).isEmpty()) {
                    bw.write("-----------------------------------------------------------------------------------" + "\n");
                    bw.write("logName:" + list[i] + "\n");
                    for (int j = 0; j < mapFile.get(list[i]).size(); j++) {
                        //System.out.println(mapFile.get(list[i]).get(j));
                        String str = String.valueOf(mapFile.get(list[i]).get(j));
                        bw.write(str + "\n");
                    }
                    bw.write("-----------------------------------------------------------------------------------" + "\n");
                }
            }
            bw.flush();
            bw.close();
            Date edate = new Date();
            System.out.println("点检完成，请检查日志！");
            System.out.println("日志保存至：" + resultUrl);
            //  统计执行时间（毫秒）
            System.out.printf("执行时长：%d 毫秒.", (edate.getTime() - sdate.getTime()));
            System.out.printf("搜索文件： %d 个.", fileCounter);
            System.out.printf("匹配日志： %d 行.", keyCounter);
        } catch (FileNotFoundException e) {
            System.out.println("找不到指定文件");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("读取文件失败");
            e.printStackTrace();
        } finally {
            try {
                a.close();
                b.close();
                c.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }*/

    // 用Element方式
    public static List<String> element(NodeList list) {
        List<String> eleList = new ArrayList<>();
        for (int i = 0; i < list.getLength(); i++) {
            Element element = (Element) list.item(i);
            NodeList childNodes = element.getChildNodes();
            for (int j = 0; j < childNodes.getLength(); j++) {
                if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE) {
                    // 获取节点值
                    eleList.add(childNodes.item(j).getFirstChild().getNodeValue());
                }
            }
        }
        return eleList;
    }

    /**
     * 读取配置文件
     *
     * @param xmlPath
     * @param key
     * @return
     */
    public static List<String> Xml2List(String xmlPath, String key) {
        // 创建解析器工厂
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = null;
        try {
            db = factory.newDocumentBuilder();
            Document doc = db.parse(xmlPath);
            NodeList nodeList = doc.getElementsByTagName(key);
            List<String> element = element(nodeList);
            return element;
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 创建一个Document对象
        return null;
    }


    public static String getFileCharsetName(File file) {
        String encoding = null;
        try {
            Path path = Paths.get(file.getPath());
            byte[] data = Files.readAllBytes(path);
            CharsetDetector charsetDetector = new CharsetDetector();
            charsetDetector.setText(data);
            CharsetMatch charsetMatch = charsetDetector.detect();
            encoding = charsetMatch.getName();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return encoding;
    }
}

